package com.tms.warehouse.mappings;

import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.tms.warehouse.Warehouse;
import com.tms.warehouse.entity.ProfileType;
import com.tms.warehouse.entity.Series;
import com.tms.warehouse.entity.Shelf;

public class ProfileTypeMapper extends AbstractMapper<ProfileType> {

	private static final String ENTITY_NAME = "ProfileType";
	private static final String PROPERTY_NAME = "name";
	private static final String PROPERTY_ARTICLE_NUMBER = "articleNumber";
	private static final String PROPERTY_SERIES = "series";
	private static final String PROPERTY_SHELF = "shelf";

	@Override
	public String getType() {

		return ENTITY_NAME;
	}

	@Override
	public ProfileType wrap(Entity entity) {

		String name = (String) entity.getProperty(PROPERTY_NAME);
		String articleNumber = (String) entity
				.getProperty(PROPERTY_ARTICLE_NUMBER);
		Key seriesKey = (Key) entity.getProperty(PROPERTY_SERIES);
		Series series = seriesKey == null ? null : Warehouse
				.findSeriesById(String.valueOf(seriesKey.getId()));
		Key shelfKey = (Key) entity.getProperty(PROPERTY_SHELF);
		Shelf shelf = shelfKey == null ? null : Warehouse.findShelfById(String
				.valueOf(shelfKey.getId()));
		long id = entity.getKey().getId();
		return new ProfileType(id, articleNumber, name, series, shelf);
	}

	@Override
	public Entity unwrap(ProfileType entity) {

		
		Entity profileType;
		if(entity.getId() > 0) {
			profileType = new Entity(createKey(entity.getId()));
		} else {
			profileType = new Entity(ENTITY_NAME);			
		}
		profileType.setProperty(PROPERTY_NAME, entity.getName());
		profileType.setProperty(PROPERTY_ARTICLE_NUMBER,
				entity.getArticleNumber());
		profileType.setProperty(PROPERTY_SERIES,
				mapRelation(entity.getSeries(), new AbstractMapper<Series>(){}));
		profileType.setProperty(PROPERTY_SHELF,
				mapRelation(entity.getShelf(), new ShelfMapper()));
		return profileType;
	}

}
